package com.bdqn.t350.controller;


import com.alibaba.fastjson.JSON;
import com.bdqn.t350.pojo.Dto;
import com.bdqn.t350.pojo.Page;
import com.bdqn.t350.pojo.SysUser;
import com.bdqn.t350.service.SysUserService;
import com.bdqn.t350.util.UploadAliYunUtil;
import com.bdqn.t350.vo.SysUserVo;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    SysUserService sysUserService;

    @GetMapping("/userListPage")
    public String userListPage(String userName,
                               Integer userRole,
                               @RequestParam(defaultValue = "1") Integer pageIndex,
                               Model model) {
        Page page = new Page();
        //设置当前页
        page.setCurrentPage(pageIndex);

        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setUserRole(userRole);
        List<SysUser> list = sysUserService.getListPageBiz(page, sysUser);
        //获得总记录数
        int count = sysUserService.getCountPageBiz(sysUser);
        page.setTotalRecord(count);
        page.setList(list);

        model.addAttribute("page", page);
        model.addAttribute("userName", userName);
        model.addAttribute("userRole", userRole);
        return "user/listPage";
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "user/add";
    }


    /**
     * 普通的文件上传
     * @param sysUser
     * @param request
     * @param titleImg
     * @return
     * @throws IOException
     */
/*    @RequestMapping("/add")
    public String add(SysUser sysUser, HttpServletRequest request,
                      @RequestParam(value = "titleImg", required = false) MultipartFile titleImg) throws IOException {
        HttpSession session = request.getSession();
        SysUser sessionSysUser = (SysUser) session.getAttribute("sysUser");
        if (sessionSysUser == null) {
            //return "redirect:/login";
            throw new RuntimeException("会话已经过期");
        } else {
            //判断文件是否为空
            if (!titleImg.isEmpty()) {
                //实现文件的保存：titleImg
                //验证文件的合法性 假设只允许上传png的后缀
                //获取文件名称
                String originalFilename = titleImg.getOriginalFilename();
                //获取文件的后缀  aa.png
                String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                if (suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpg")) {
                    if (titleImg.getSize() < 500000) {
                        //确认文件上传的路径
                        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uloadfiles");
                        File targetFile = new File(path);
                        //判断路径是否存在
                        if (!targetFile.exists()) {
                            targetFile.mkdirs();
                        }
                        //生成保存文件的随机数
                        String saveFile = System.currentTimeMillis() + "." + suffix;
                        titleImg.transferTo(new File(targetFile, saveFile));
                        sysUser.setSaveFileName(saveFile);
                        sysUser.setRealFileName(originalFilename);
                    } else {
                        request.setAttribute("uploadFileError", "文件大小超过500000");
                        return "user/add";
                    }
                } else {
                    request.setAttribute("uploadFileError", "文件格式错误,必须是jpg或者png");
                    return "user/add";
                }
            }
            sysUser.setCreatedBy(sessionSysUser.getCreatedBy());
            sysUser.setCreationDate(new Date());
            int count = sysUserService.addService(sysUser);
            if (count < 1) {
                throw new RuntimeException("添加失败,请重新登录");
            }
            return "redirect:/user/userListPage";
        }
    }*/

    /**
     * 调用oss的文件上传
     *
     * @param sysUser
     * @param request
     * @param titleImg
     * @return
     * @throws IOException
     */
    @RequestMapping("/add")
    public String add(SysUser sysUser, HttpServletRequest request,
                      @RequestParam(value = "titleImg", required = false) MultipartFile titleImg) throws IOException {
        //判断文件是否为空
        if (!titleImg.isEmpty()) {
            //获取文件真实名称
            String originalFilename = titleImg.getOriginalFilename();
            //获取文件的后缀  aa.png
            String suffix = originalFilename.substring(titleImg.getOriginalFilename().lastIndexOf(".") + 1);
            if (suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpg")) {
                if (titleImg.getSize() < 500000) {
                    //生成保存文件的随机数
                    String saveFile = System.currentTimeMillis() + "." + suffix;
                    boolean bool = UploadAliYunUtil.uploadImage(titleImg, saveFile);
                    if (bool) {
                        sysUser.setSaveFileName(saveFile);
                        sysUser.setRealFileName(originalFilename);
                    }
                } else {
                    request.setAttribute("uploadFileError", "文件大小超过500000");
                    return "user/add";
                }
            } else {
                request.setAttribute("uploadFileError", "文件格式错误,必须是jpg或者png");
                return "user/add";
            }
        }
        sysUser.setCreatedBy(((SysUser) request.getSession().getAttribute("sysUser")).getCreatedBy());
        sysUser.setCreationDate(new Date());
        int count = sysUserService.addService(sysUser);
        if (count < 1) {
            throw new RuntimeException("添加失败,请重新登录");
        }
        return "redirect:/user/userListPage";
    }

    //声明一个局部异常，当出现异常就会进入该方法
//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e, HttpServletRequest request) {
//        request.setAttribute("e", e);
//        return "login";
//    }


/*    @RequestMapping("/view")
    public String view(@RequestParam(name = "id") String id, HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        SysUser sessionSysUser = (SysUser) session.getAttribute("sysUser");
        if (sessionSysUser == null) {
            //return "redirect:/login";
            throw new RuntimeException("会话已经过期");
        } else {
            SysUserVo sysUser = sysUserService.getByUserId(Integer.parseInt(id));
            model.addAttribute("sysUser", sysUser);
            return "user/view";
        }
    }*/


    @ResponseBody
    @RequestMapping(value = "/view", produces = {"application/json;charset=UTF-8"})
    public Object view(@RequestParam(name = "id") String id, HttpServletRequest request, Model model) {
        SysUserVo sysUser = sysUserService.getByUserId(Integer.parseInt(id));
        Dto dto = new Dto();
        dto.setMsg("成功!");
        dto.setData(sysUser);
        dto.setErrorCode("200");
        dto.setSuccess("success");
        //   return JSON.toJSONString(dto);
        return dto;
    }

/*    @ResponseBody
    @RequestMapping(value = "/deleteById")
    public Object deleteById(@RequestParam(name = "id") String id, HttpServletRequest request, Model model) {
        int count = sysUserService.deleteByIdBiz(Integer.parseInt(id));
        Dto dto = new Dto();
        if (count > 0) {
            dto.setMsg("成功!");
            dto.setErrorCode("6666");
            dto.setSuccess("success");
        } else {
            dto.setMsg("失败!");
            dto.setErrorCode("9999");
            dto.setSuccess("error");
        }
        return dto;
    }*/

    @ResponseBody
    @RequestMapping(value = "/deleteById/{id}/delete")
    public Object deleteById(@PathVariable String id, HttpServletRequest request, Model model) {
        int count = sysUserService.deleteByIdBiz(Integer.parseInt(id));
        Dto dto = new Dto();
        if (count > 0) {
            dto.setMsg("成功!");
            dto.setErrorCode("6666");
            dto.setSuccess("success");
        } else {
            dto.setMsg("失败!");
            dto.setErrorCode("9999");
            dto.setSuccess("error");
        }
        return dto;
    }
}
